package com.kele.realm;

import com.kele.entity.User;
import com.kele.service.UserService;
import com.kele.service.impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Version 2019
 * @Author:kele
 * @Date:2020/10/29
 * @Content:
 * @Description：
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserServiceImpl userService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前用户的对象
        Subject subject = SecurityUtils.getSubject();
        //获取当前用户的认证信息
        User currentUser = (User) subject.getPrincipal();
        //给获取的当前用户的信息设置权限
        info.addStringPermission(currentUser.getRole());


        return info;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

//        //先给个假数据试验一下验证
//        String username="root";
//        String password="123456";

        // 加密方式
        String hashAlgorithName = "MD5";
        // 加密次数
        int hashIterations = 1024;
        UsernamePasswordToken userToken= (UsernamePasswordToken) token;
        //来连接数据库
        User user = userService.findUserByName(userToken.getUsername());
        if (user==null){
            return null;//UnknownAccountException
        }


        //密码认证由shiro自己去做
        /**
         * 三个参数：第一个获取当前用户的认证
         *          第二个是传过来的密码的对象
         *          第三个是认证的用户名
         */

        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
